package chess

type Room struct {
	running    bool
	kill       uint8
	operate    uint8
	current    *Player
	next       *Player
	chessboard *Chessboard
}

func (room *Room) Handle() {
	for {
		if !room.running {
			break
		}
		room.play()
	}
}

func (room *Room) play() {
	var om coperate
	room.next.ReadMessage(om)
	err := room.next.connection.ReadJSON(om)
	if err != nil {
		if om.code == 301 {
			//一方请降
		}
	}
	action := room.current.action
	switch action {
	case 1:
		room.chess_put()
	case 2:
		room.chess_kill()
	case 3:
		room.chess_move()
	}
}

func (room *Room) chess_put() {
	var message messageput
	err := room.current.connection.ReadJSON(message)
	if err != nil {
		location := uint8(message.location)
		ret := room.chessboard.PutPiece(location, room.current.TakePiece())
		if ret.code == 0 {
			response := putresponse{0, message.location}
			room.current.SendMessage(response)
			room.next.SendMessage(response)
			//room.swap_player() //落子成功 判定成三
			room.check_three(uint8(location))
		} else {
			response := putresponse{uint32(ret.code), 0}
			room.current.SendMessage(response)
		}
	}
}

func (room *Room) chess_kill() {
	var message messagekill
	err := room.current.connection.ReadJSON(message)
	if err != nil {
		location := uint8(message.location)
		ret := room.chessboard.PutPiece(location, room.current.TakePiece())
		if ret.code == 0 {
			response := killresponse{0, message.location}
			room.current.SendMessage(response)
			room.next.SendMessage(response)
			if room.kill == 0 {
				room.swap_player()
			}
		} else {
			response := killresponse{uint32(ret.code), 0}
			room.current.SendMessage(response)
		}
	}
}

func (room *Room) chess_move() {
	var message messagemove
	err := room.current.connection.ReadJSON(message)
	if err != nil {
		location := message.source
		direct := message.direct
		ret := room.chessboard.MovePiece(uint8(location), uint8(direct), room.current.color)
		if ret.code == 0 {
			//走子成功 判定成三
			//room.check_three(uint8(location))
		} else {
			response := moveresponse{uint32(ret.code), 0, 0}
			room.current.SendMessage(response)
		}
	}
}

func (room *Room) check_three(location uint8) {
	ret := room.chessboard.CheckThree(location)
	if ret > 0 {
		room.kill = ret
		br := nextaction{true, 301}
		room.current.SendMessage(br)
		wr := nextaction{false, 301}
		room.next.SendMessage(wr)
	} else {
		br := next_action(false, room.current.pieces)
		room.current.SendMessage(br)
		wr := next_action(true, room.next.pieces)
		room.next.SendMessage(wr)
		room.swap_player()
	}
}

//交换位置
func (room *Room) swap_player() {
	temp := room.next
	room.next = room.current
	room.current = temp
}

func NewRoom(current *Player, next *Player) Room {
	return Room{
		true,
		0,
		0,
		current,
		next,
		NewChessboard(),
	}
}

const (
	Put  = 1
	Move = 2
	Kill = 3
)
